package cn.itcast.demo;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/ServletDemo03")
public class ServletDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        获取图片绝对路径
        String realPath = getServletContext().getRealPath("/img/1.jpg");
//      创建字节流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath));
//       边读边写
        ServletOutputStream os = resp.getOutputStream();
        byte[] bytes =new byte[1024];
        int len;
        while ((len = bis.read(bytes))!= -1){
            os.write(bytes,0,len);
        }
        bis.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
